package lib.bone.admin.controller.system;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lib.bone.common.constant.ResponseCodeConst;
import lib.bone.common.core.domain.ResponseDTO;
import lib.bone.system.dao.SysRoleMenuDAO;
import lib.bone.system.domain.dto.LoginBody;
import lib.bone.system.domain.entity.*;
import lib.bone.system.domain.vo.RouterVO;
import lib.bone.system.domain.vo.SysDeptVO;
import lib.bone.system.domain.vo.SysUserVO;
import lib.bone.system.service.SysDeptService;
import lib.bone.system.service.SysMenuService;
import lib.bone.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author : Kindear
 * @Date : 2021-12-3
 *
 */
@RestController
@Api(tags = "登录管理")
public class SysLoginController {
    @Autowired
    SysUserService sysUserService;

    @Autowired
    SysDeptService sysDeptService;

    @Autowired
    SysMenuService sysMenuService;

    @Autowired
    SysRoleMenuDAO sysRoleMenuDAO;

    @PostMapping(value = {"system/login","login"})
    @ApiOperation(value = "用户登录",notes = "")
    public ResponseDTO login(@RequestBody @Validated LoginBody loginBody){
        return sysUserService.userLogin(loginBody);
    }

    @GetMapping(value = "isOrigin")
    @ApiOperation(value = "判断是否为初始密码")
    public ResponseDTO isOrigin(){
        Long loginId = StpUtil.getLoginIdAsLong();

        Optional<SysUser> userOp = sysUserService.getById(loginId);
        if(!userOp.isPresent()){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"ID: ["+loginId+"]对应用户不存在!");
        }
        SysUser sysUser = userOp.get();
        if (sysUser.getPassword().equals("123456")){
            return ResponseDTO.succData(1);
        }
        return ResponseDTO.succData(0);
    }

    /**
     * 获取用户信息
     */
    @GetMapping(value = {"userInfo","system/userInfo"})
    @ApiOperation(value = "用户信息",notes = "只有登录态用户调用该接口可以获取到信息")
    public ResponseDTO getUserInfo(){
        // 获取当前登录账号信息
        Long loginId = StpUtil.getLoginIdAsLong();

        Optional<SysUser> userOp = sysUserService.getById(loginId);
        if(!userOp.isPresent()){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"ID: ["+loginId+"]对应用户不存在!");
        }

        SysUserVO sysUserVO = new SysUserVO();

        BeanUtil.copyProperties(userOp.get(),sysUserVO, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));

        /**
         * 获取部门信息
         */
        Optional<SysDept> sysDeptOp = sysDeptService.getById(userOp.get().getDeptId());

        SysDeptVO sysDeptVO = new SysDeptVO();

        sysDeptOp.ifPresent(sysDept -> BeanUtil.copyProperties(sysDept, sysDeptVO, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true)));


        sysUserVO.setSysDeptVO(sysDeptVO);

//        Set<String> roleKeySet = new HashSet<>();

        Set<String> permsSet = new HashSet<>();

//        Set<Long> roleIdList = new HashSet<>();
        /**
         * 获取用户角色列表
         */
        Set<SysRole> sysRoleSet = userOp.get().getRoles();

        for (SysRole sysRole:sysRoleSet){
//            roleIdList.add(sysRole.getId());
//            roleKeySet.add(sysRole.getRoleKey());
            List<String> perms = sysRole.getPermission();
            permsSet.addAll(perms);
        }
        //清理空值权限
        permsSet.remove("");
        /**
         * 赋值角色和权限
         */
        sysUserVO.setRoles(sysRoleSet);
        sysUserVO.setPermissions(permsSet);

        return ResponseDTO.succData(sysUserVO);
    }
    /**
     * 用户登出
     * method : POST
     */
    @PostMapping(value = {"logout","system/logout"})
    @ApiOperation(value = "用户登出",notes = "")
    public ResponseDTO userLogout(HttpServletRequest request, HttpServletResponse response){
        return sysUserService.userLogout();
    }
    /**
     * 获取用户路由
     */
    @GetMapping(value = {"routers","system/routers"})
    @ApiOperation(value = "获取路由",notes = "")
    public ResponseDTO getRouters(){
        /**
         * 获取登录用户
         */
        Long userId = StpUtil.getLoginIdAsLong();

        Optional<SysUser> sysUserOp = sysUserService.getById(userId);

        /**
         * 获取角色集合
         */
        if(!sysUserOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.UNAUTHORIZED);
        Set<SysRole> roleSet = sysUserOp.get().getRoles();

        List<Long> roleIdList = new ArrayList<>();

        for(SysRole sysRole:roleSet){
            roleIdList.add(sysRole.getId());
        }
        /**
         * 计算菜单列表
         */
        List<SysRoleMenu> sysRoleMenuList = sysRoleMenuDAO.findByRoleIdIn(roleIdList);

        List<Long> menuIdList = new ArrayList<>();

        for(SysRoleMenu sysRoleMenu:sysRoleMenuList){
            menuIdList.add(sysRoleMenu.getMenuId());
        }
        // 去重处理
        menuIdList = menuIdList.stream().distinct().collect(Collectors.toList());
        //Boolean isext = menuIdList.contains(1L);

        /**
         * 查询菜单列表
         */
        List<SysMenu> sysMenuList = sysMenuService.findByParent(null);
//        for (SysMenu menu:sysMenuList){
//            if (menu.getChildren().size() == 0){
//
//            }
//        }

        /**
         * 构建返回信息
         */
        List<RouterVO> routerVOList = sysMenuService.buildMenus(sysMenuList,menuIdList);


        return ResponseDTO.succData(routerVOList);

    }
}
